/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package core;

import datamodel.Order;
import datamodel.Order4;
import datamodel.StorageInformer;
import datastorage.OrderManagerStorage;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import network.Connection;
import network.PacketBuilder;
import network.packets.CallSignChangedResponce;
import network.packets.GetOrdersResponse;
import network.packets.OrderResponce;
import network.packets.Packet;

/**
 *
 * @author Kvest
 */
public class OrderManager 
{
    public static final int GO_OK = 0;
    public static final int GO_IS_DELETED = 1;
    
    public static final int NO_ORDER_ID = -1;
    private static final int DEFAULT_T = 60000;
    private static final int DEFAULT_MAX_ORDERS_COUNT = 3;
    private static final long CLEAR_TIMEOUT = 2000;
    
    private final Vector orders = new Vector();
    private Vector currentOrders; 
    
    private OrderManagerStorage storage;
    
    private int[] T;
    private int maxOrdersCount;
    
    private CountChanged countChangedListener = null;
    private OrderEvents orderEventsListener = null;
    private PreordersCountChanged preordersCountChangedListener = null;
        
    private Timer clearTimer;
    
    public OrderManager()
    {
        storage = new OrderManagerStorage();
        currentOrders = new Vector();
        
        T = new int[3];
        T[0] = DEFAULT_T;
        T[1] = DEFAULT_T;
        T[2] = DEFAULT_T;
        maxOrdersCount = DEFAULT_MAX_ORDERS_COUNT;

        load();
        
        registerNetworkNotifiers();
        
        //Запускаем таймер удаления
        startClearTimer();
    }
    
    public final void load()
    {
        clear();
        
        synchronized(orders)
        {
            storage.load(orders);
        }
    }
    
    public void save()
    {
        synchronized(orders)
        {
            storage.save(orders);
        }
    }
    
    private void startClearTimer()
    {
        clearTimer = new Timer();
        clearTimer.schedule(new TimerTask() 
        {
            public void run() 
            {            
                autoClear();
            }
        }, CLEAR_TIMEOUT, CLEAR_TIMEOUT);
    }
    
    public void clear()
    {
        synchronized(orders)
        {
            orders.removeAllElements();
        }
        currentOrders.removeAllElements();
    }
    
    public void deleteAll()
    {
        //Удалям все из памяти
        clear();
        
        //Удаляем все с RMS
        storage.clear();
    }
    
    public StorageInformer getStorageMemoryInfo()
    {
        return storage;
    }
    
    public void setT(int T0, int T1, int T2)
    {
        T[0] = T0;
        T[1] = T1;
        T[2] = T2;
    }

    public void setMaxOrdersCount(int maxOrdersCount) 
    {
        this.maxOrdersCount = maxOrdersCount;
    }

    public Vector getEfirOrders()
    {
        Vector result = new Vector();
        synchronized(orders)
        {
            for(int i = 0; i < orders.size(); ++i)
            {
                if (((Order)orders.elementAt(i)).getStatus() == Order.STATE_NEW)
                {
                    result.addElement(orders.elementAt(i));
                }
            }
        }
        
        return result;
    }   
    
    public Vector getCurrentOrders()
    {
        Vector result = new Vector();
        synchronized(orders)
        {
            for(int i = 0; i < orders.size(); ++i)
            {
                if (((Order)orders.elementAt(i)).getStatus() == Order.STATE_PERFORMING || 
                    ((Order)orders.elementAt(i)).getStatus() == Order.STATE_TAKEN)
                {
                    result.addElement(orders.elementAt(i));
                }
            }
        }
        
        return result;
    }
    
    public Vector getCompleteOrders()
    {
        Vector result = new Vector();
        synchronized(orders)
        {
            for(int i = 0; i < orders.size(); ++i)
            {
                if (((Order)orders.elementAt(i)).getStatus() == Order.STATE_PERFORMED || 
                    ((Order)orders.elementAt(i)).getStatus() == Order.STATE_MISSED || 
                    ((Order)orders.elementAt(i)).getStatus() == Order.STATE_CANCELLED)
                {
                    result.addElement(orders.elementAt(i));
                }
            }
        }
        
        return result;
    }
    
    private void processIncomingOrder(Order order, boolean emitEvent)
    {
        if (order.getFolder().equals("Невыполненный") || order.getFolder().equals("Корзина"))
        {
            cancelOrder(order.getOrderID(), "Отмененный", emitEvent);
        }
        else if (order.getFolder().equals("Выполненный"))
        {
            //Если такого заказа нет - добавляем
            boolean notFound = true;
            synchronized(orders)
            {
                for(int i = 0; i < orders.size(); ++i)
                {
                    if (((Order)orders.elementAt(i)).getOrderID() == order.getOrderID())
                    {
                        order = (Order)orders.elementAt(i);
                        notFound = false;
                        break;
                    }
                }
            }
                    
            if (notFound)
            { 
                //Добавляем заказ в коллекцию
                synchronized(orders)
                {
                    orders.insertElementAt(order,0);
                }
            }

            //Устанавливаем соответствующие свойства
            order.setStatus(Order.STATE_PERFORMED);
            
            //Удаляем его из очереди заказов
            for (int i=0;i<currentOrders.size();++i)
            {
                if (((Integer)currentOrders.elementAt(i)).intValue() == order.getOrderID())
                {
                    currentOrders.removeElementAt(i);
                    break;
                }
            }

            //Генерируем события
            if (emitEvent)
            {
                completeOrderEvent(order);
            }
        }
        else if (order.getOrderType().equals("FindDriver1") || order.getOrderType().equals("FindDriver2") ||
            order.getOrderType().equals("FindDriver3"))
        {

            order.setN(Integer.parseInt(order.getOrderType().substring(10)));

            //Если заказ с таким Id есть - удаляем
            deleteOrderWithoutEvent(order.getOrderID());

            //Добавляем заказ в коллекцию
            synchronized(orders)
            {
                orders.insertElementAt(order, 0);
            }
           
            //Генерируем события
            if (emitEvent)
            {
                newOrderEvent(order);
            }
        }
        else if ((order.getOrderType().equals("SendedByDispatcherFromGetFolder"))||(order.getOrderType().equals("SendedByDispatcher")))
        {
            int orderID = order.getOrderID();
            String folder = order.getFolder();
                   
            //Проверяем нет ли такого заказа в списке выполняемых
            boolean notExists = true;
            for (int i = 0; i < currentOrders.size(); ++i)
            {
                if (((Integer)currentOrders.elementAt(i)).intValue() == orderID)
                {
                    notExists = false;
                    break;
                }
            }

            if (notExists && (!folder.equals("Автопоиск") && !folder.equals("НаОформлении") && 
                              !folder.equals("Входящий"))  && !folder.equals("Принятый"))
            {
                currentOrders.addElement(new Integer(orderID));
            }

            //Ищем заказ с таким ИД
            boolean found = false;
            synchronized(orders)
            {
                for(int i = 0 ; i < orders.size(); ++i)
                {
                    if (((Order)orders.elementAt(i)).getOrderID() == orderID)
                    {
                        found = true;
                        //Изменяем соответствующие свойства
                        order.setStatus(((Order)orders.elementAt(i)).getStatus());
                        order.setN(((Order)orders.elementAt(i)).getN());
                        order.setPreliminary(((Order)orders.elementAt(i)).isPreliminary());
//                        order.setSigned(((Order)orders.elementAt(i)).getSigned());

                                        
			//Обновляем информацию
                        if (folder.equals("Автопоиск") || folder.equals("Входящий"))
                        {
                            order.setStatus(Order.STATE_NEW);
                        }
                        else if (folder.equals("НаОформлении") || folder.equals("Принятый"))
                        {
                            order.setStatus(Order.STATE_TAKEN);
                        }
                        else if (folder.equals("Направленный") || folder.equals("Исполняемый"))
                        {
                            order.setStatus(Order.STATE_PERFORMING);
                        }
                        
                        //Заменяем заказ
                        orders.setElementAt(order, i);
                        
                        break;
                    }
                }
            }

            if (!found)
            {
                //Устанавливаем соответствующие свойства
                if (folder.equals("Автопоиск") || folder.equals("Входящий"))
                {
                    order.setStatus(Order.STATE_NEW);
                }
                else if (folder.equals("НаОформлении") || folder.equals("Принятый"))
                {
                    order.setStatus(Order.STATE_TAKEN);
                }
                else if (folder.equals("Направленный") || folder.equals("Исполняемый"))
                {
                    order.setStatus(Order.STATE_PERFORMING);
                }
                
                //Добавляем заказ
                synchronized(orders)
                {
                    orders.insertElementAt(order, 0);
                }
            }
            
            //Генерируем событие
            if (emitEvent)
            {
                orderUpdatedEvent(order);
            }
        }    
    }

    public void autoClear()
    {   
        boolean changed = false;
        synchronized(orders)
        {            
            Order order;
            int oldState;
            int canceledCount = 0;
            int missedCount = 0;
            int performedCount = 0;
                
            for(int i = orders.size() - 1; i >= 0; --i)
            {           
                order = (Order)orders.elementAt(i);
                if (order == null)
                {
                    continue;
                }
                
                oldState = order.getStatus();
                if (order.isTooOld(T))
                {
                    orders.removeElementAt(i);

                    changed = true;

                    //Генерируем событие
                    deleteOrderEvent(order);
                } else { 
                    if (oldState != order.getStatus())
                    {
                        changed = true;

                        //Генерируем событие
                        orderStateChangedEvent(order);
                    }
               
                    if (order.getStatus() == Order.STATE_CANCELLED) {
                        canceledCount++;
                    } else if (order.getStatus() == Order.STATE_MISSED) {
                        missedCount++;
                    } else if (order.getStatus() == Order.STATE_PERFORMED) {
                        performedCount++;
                    }
                }
            }

            int maxArchivOrdersCount = Settings.getSettings().getMaxArchivOrdersCount();
            for(int i = orders.size() - 1; (i >= 0) && (canceledCount > maxArchivOrdersCount ||
                                                        missedCount > maxArchivOrdersCount || 
                                                        performedCount > missedCount); --i) {
                order = (Order)orders.elementAt(i); 
                if (order.getStatus() == Order.STATE_CANCELLED && canceledCount > maxArchivOrdersCount) {
                    orders.removeElementAt(i);
                    canceledCount--;
                } else if (order.getStatus() == Order.STATE_MISSED && missedCount > maxArchivOrdersCount) {
                    orders.removeElementAt(i);
                    missedCount--;
                } else if (order.getStatus() == Order.STATE_PERFORMED && performedCount > maxArchivOrdersCount) {
                    orders.removeElementAt(i);
                    performedCount--;
                }
            }
        }

        if (changed)
        {
            countChangedEvent();
        }        
    }
    
    public Order getCurrentOrder()
    {
        int currentOrderID = currentOrder();
        if (currentOrderID != NO_ORDER_ID)
        {
            return getOrder(currentOrderID);
        }
        else
        {
            return null;
        }
    }
    
    public Order getOrder(int orderId)
    {
        synchronized(orders)
        {
            for(int i = 0; i < orders.size(); ++i)
            {
                if (((Order)orders.elementAt(i)).getOrderID() == orderId)
                {
                    return (Order)orders.elementAt(i);
                }
            }
        }
        
        return null;
    }
    
    public void deleteOrderWithoutEvent(int orderId)
    {
        synchronized(orders)
        {
            for(int i = 0; i < orders.size(); ++i)
            {
                if (((Order)orders.elementAt(i)).getOrderID() == orderId)
                {
                    orders.removeElementAt(i);
                    break;
                }
            }
        }
    }
    
    public void cancelOrder(int orderID)
    {
        cancelOrder(orderID, "Отмененный", true);
        
        //Генерируем событие изменения состояния
        countChangedEvent();
    }
    
    private void cancelOrder(int orderID, String folder, boolean emitEvent)
    {
        //Удаляем заказ из очереди на выполнение
        for (int i = 0; i < currentOrders.size(); ++i)
        {
            if (((Integer)currentOrders.elementAt(i)).intValue() == orderID)
            {
                currentOrders.removeElementAt(i);
                break;
            }
        }
        
        //Ищем заказ с таким ИД и помечаем eго как отмененный
        Order order = null;
        boolean deleted = false;
        synchronized(orders)
        {
            for(int i = 0; i < orders.size(); ++i)
            {
                if (((Order)orders.elementAt(i)).getOrderID() == orderID)
                {
                    order = (Order)orders.elementAt(i);
                    order.setFolder(folder);

//                    if (order.getStatus()== Order.STATE_TAKEN)
//                    {
//                        claimedOrdersCount--;
//                    }

                    if (order.isNewEfirOrder())
                    {
                        orders.removeElementAt(i);
                        deleted = true;
                    }
                    else
                    {
                        order.setStatus(Order.STATE_CANCELLED);
                    }
                    break;
                }
            }
        }
        
        //Генерируем события
        if (order != null && emitEvent)
        {
            if (deleted)
            {
                deleteOrderEvent(order);
            }
            else
            {
                cancelOrderEvent(order);
            }
        }
    }
    
    public int currentOrder()
    {
        if (currentOrders.size() > 0)
        {
            return ((Integer)currentOrders.elementAt(0)).intValue();
        }
        else
        {
            return NO_ORDER_ID;
        }
    }
    
    public void sendCloseOrderRequest()
    {
        int currentOrder = currentOrder();
        if (currentOrder != NO_ORDER_ID)
        {
            //Формируем данные для заявки
            RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
            byte[] body = PacketBuilder.createBodyOrderAnswer(currentOrder , "Done", "", runtimeData.getPeopleID());
            byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
            //Отправляем данные
            Connection.getConnection().send(data);
            
            //Удаляем заказ из очереди заказов
            if (currentOrders.size() > 0)
            {
                currentOrders.removeElementAt(0);
            }
            
            //Сбрасываем текущий заказ
            Order order = getOrder(currentOrder);
            if (order != null)
            {
                order.setStatus(Order.STATE_PERFORMED);
                
                orderStateChangedEvent(order);
                countChangedEvent();
            }
        }
    }
    
    public void sendRefuseOrderRequest()
    {
        int currentOrder = currentOrder();
        if (currentOrder != NO_ORDER_ID)
        {
            //Генерируем данные
            RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
            byte[] body = PacketBuilder.createBodyOrderCancel(currentOrder, PacketBuilder.REASON_REFUSE, runtimeData.getPeopleID());
            byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
            //Отправляем данные
            Connection.getConnection().send(data);
        }
    }
    
    public void sendWithPassengerRequest()
    {
        int currentOrder = currentOrder();
        if (currentOrder != NO_ORDER_ID)
        {
            //Генерируем данные
            RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
            byte[] body = PacketBuilder.createBodyOrderAnswer(currentOrder,"StartDoOrder","", runtimeData.getPeopleID());
            byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
            //Отправляем данные
            Connection.getConnection().send(data);
        }
    }
    
    public void sendCarOnAddressRequest()
    {
        int currentOrder = currentOrder();
        if (currentOrder != NO_ORDER_ID)
        {
            //Генерируем данные
            RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
            byte[] body = PacketBuilder.createBodyCarOnAddressRequest(currentOrder, runtimeData.getPeopleID());
            byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
            //Отправляем данные
            Connection.getConnection().send(data);
        }
    }
    
    public void connectToClient() {
        int currentOrder = currentOrder();
        if (currentOrder != NO_ORDER_ID) {
            //Генерируем данные
            RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
            byte[] body = PacketBuilder.createBodyCW_ConnectDriverClient(currentOrder, runtimeData.getPeopleID());
            byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
            //Отправляем данные
            Connection.getConnection().send(data);
        }
    }
    
    public void sendLateRequest(int time)
    {
        int currentOrder = currentOrder();
        if (currentOrder != NO_ORDER_ID)
        {
            //Генерируем данные
            RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
            byte[] body = PacketBuilder.createDriverDelay(currentOrder, time, runtimeData.getPeopleID());
            byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
            //Отправляем данные
            Connection.getConnection().send(data);
        }
    }
    
    public void sendPassengerOutRequest(int time)
    {
        int currentOrder = currentOrder();
        if (currentOrder != NO_ORDER_ID)
        {
            //Генерируем данные
            RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
            byte[] body = PacketBuilder.createPassengerOut(currentOrder, time, runtimeData.getPeopleID());
            byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
            //Отправляем данные
            Connection.getConnection().send(data);
        }
    }
    
    public void signPrelimOrder(Order order)
    {
        //Генерируем данные
        RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
        byte[] body = PacketBuilder.createSignPreliminaryOrder(order.getOrderID(), Settings.getSettings().getCallsign(), runtimeData.getPeopleID());
	byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        //Отправляем данные
        Connection.getConnection().send(data);
    }
    
    public int getOrderRequest(Order order, int time)
    {        
        //Проверяем, не истекло ли еще время заказа   
	if (order.isDeleted(T))
        {
            return GO_IS_DELETED;
        }

        //Отправляем заявку
	RuntimeData runtimeData = IMAPMIDlet.getMidlet().getRuntimeData();
        byte[] body = PacketBuilder.createBodyOrderAnswer(order.getOrderID(), "CanGetOrder", Integer.toString(time), runtimeData.getPeopleID());
        byte[] data = PacketBuilder.createSrvTransfereData(PacketBuilder.DEFAULT_CONNECTION_TYPE, runtimeData.getSrvID(), 
                                                           PacketBuilder.DEFAULT_DESTINATION_ID, runtimeData.getGUID(), true, body);
        Connection.getConnection().send(data);

	//изменяем статус заказа
        int oldState = order.getStatus();
        order.setStatus(Order.STATE_TAKEN);
        
        //Генерируем события
        if (oldState != Order.STATE_TAKEN)
        {
            orderStateChangedEvent(order);
            countChangedEvent();
        }
        //ToDo Kvest возможно потом пригодится
//        //Запоминаем время подачи
//        rd.addGivingTime(rd.getShownOrder(), additional);
//        //Сбрасываем фильтры
//        orderManager.setMinSum(-1);
//        regionsFilterForm.selectAll();
//        //сохранить фильтр
//        Settings.getSettings().setFilter(regionsFilterForm.getString());
        
        return GO_OK;
    }
    
    private int[] calculateCounts()
    {
        int[] result = new int[3]; //Новых, текущих, завершенных
        synchronized(orders)
        {
            int state;
            for (int i = 0; i < orders.size(); ++i)
            {
                state = ((Order)orders.elementAt(i)).getStatus();
                if (state == Order.STATE_NEW)
                {
                    ++result[0];
                }
                else if (state == Order.STATE_PERFORMING || state == Order.STATE_TAKEN)
                {
                    ++result[1];
                }
                else if (state == Order.STATE_PERFORMED || state == Order.STATE_MISSED || state == Order.STATE_CANCELLED)
                {
                    ++result[2];
                }
            }
        }
        
        return result;
    }
    
    public void setPreordersCount(int count)
    {
        //Просто дергаем подписчика
        preordersCountChangedEvent(count);
    }
    
    private void registerNetworkNotifiers()
    {
        Connection.getConnection().setPacketListener(Packet.GET_ORDERS_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                GetOrdersResponse responce = (GetOrdersResponse)packet;

                for (int i = 0; i < responce.count(); ++i)
                {
                    //Обрабатываем новый заказ
                    try
                    {
                        processIncomingOrder(responce.getOrder(i), false);
                    }catch(Exception e){}
                }
                
                //Генерируем событие изменения количества заказов
                countChangedEvent();
            }
        });

        Connection.PacketNotifier newOrderNotifier = new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                processIncomingOrder(((OrderResponce)packet).getOrder(), true);
                
                //Генерируем событие изменения количества заказов
                countChangedEvent();
            }
        };

        Connection.getConnection().setPacketListener(Packet.ORDER_RESPONCE,newOrderNotifier);
        Connection.getConnection().setPacketListener(Packet.ORDER_RESPONCE2,newOrderNotifier);
        Connection.getConnection().setPacketListener(Packet.ORDER_RESPONCE3,newOrderNotifier);
        Connection.getConnection().setPacketListener(Packet.ORDER_RESPONCE4,newOrderNotifier);
        
        Connection.getConnection().setPacketListener(Packet.CALL_SIGNCHANGED_RESPONCE, new Connection.PacketNotifier()
        {
            public void incomingPacket(Packet packet)
            {
                CallSignChangedResponce responce = (CallSignChangedResponce)packet;
                
                //Просто отменяем заказ
                if (responce.getOrderID() != -1)
                {
                    cancelOrder(responce.getOrderID());
                }
            }
        });
    }

    public void setCountChangedListener(CountChanged countChangedListener) 
    {
        this.countChangedListener = countChangedListener;
        
        //Сразу генерируем событие
        countChangedEvent();
    } 
    
    private void countChangedEvent()
    {
        if (countChangedListener != null)
        {
            countChangedListener.countChanged(calculateCounts());
        }
    }

    public void setOrderEventsListener(OrderEvents orderEventsListener) 
    {
        this.orderEventsListener = orderEventsListener;
    }

    public void setPreordersCountChangedListener(PreordersCountChanged preordersCountChangedListener) 
    {
        this.preordersCountChangedListener = preordersCountChangedListener;
        
        //Сразу генерируем событие
        preordersCountChangedEvent(0);
    }
    
    private void completeOrderEvent(Order order)
    {
        //Оповещение
        NotificationManager.getNotificationManager().event(NotificationManager.ORDER_STATE_CHANGED);
                
        if (orderEventsListener != null)
        {
            orderEventsListener.completeOrder(order);
        }
    }
    
    private void newOrderEvent(Order order)
    {
        //Оповещение
        if (order.isEfirOrder())
        {
            NotificationManager.getNotificationManager().event(NotificationManager.NEW_EFIR_ORDER);
        }
        else
        {
            NotificationManager.getNotificationManager().event(NotificationManager.NEW_ORDER);
        }
        
        if (orderEventsListener != null)
        {
            orderEventsListener.newOrder(order);
        }
    }
    
    private void deleteOrderEvent(Order order)
    {
        if (orderEventsListener != null)
        {
            orderEventsListener.deleteOrder(order);
        }
    }
    
    private void cancelOrderEvent(Order order)
    {
        //Оповещение
        NotificationManager.getNotificationManager().event(NotificationManager.ORDER_CANCELED);
        
        if (orderEventsListener != null)
        {
            orderEventsListener.cancelOrder(order);
        }
    }
    
    private void orderUpdatedEvent(Order order)
    {
        //Оповещение
        NotificationManager.getNotificationManager().event(NotificationManager.ORDER_STATE_CHANGED);

        if (orderEventsListener != null)
        {
            orderEventsListener.orderUpdated(order);
        }
    }
    
    private void orderStateChangedEvent(Order order)
    {
        if (orderEventsListener != null)
        {
            orderEventsListener.orderStateChanged(order);
        }
    }
    
     private void preordersCountChangedEvent(int count)
     {
         if (preordersCountChangedListener != null)
         {
             preordersCountChangedListener.preordersCountChanged(count);
         }
     }
    
    public interface PreordersCountChanged
    {
        public void preordersCountChanged(int count);
    }
    
    public interface CountChanged
    {
        public void countChanged(int[] counts);
    }
    
    public interface OrderEvents
    {
        public void newOrder(Order order);    
        public void deleteOrder(Order order); 
        public void cancelOrder(Order order); 
        public void completeOrder(Order order); 
        public void orderUpdated(Order order);
        public void orderStateChanged(Order order); 
    }
}
